package com.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution210 {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] rudu = new int[numCourses];
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            list.add(new ArrayList<>());
        }
        for (int[] edge : prerequisites) {
            rudu[edge[0]]++;
            list.get(edge[1]).add(edge[0]);
        }
        int index = 0;
        int[] res = new int[numCourses];
        int count = numCourses;
        LinkedList<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (rudu[i] == 0) {
                queue.add(i);
                res[index++] = i;
                count--;
            }
        }
        while (!queue.isEmpty()) {
            int curNum = queue.removeFirst();
            List<Integer> numList = list.get(curNum);
            for (int x : numList) {
                rudu[x]--;
                if (rudu[x] == 0) {
                    queue.add(x);
                    res[index++] = x;
                    count--;
                }
            }
        }
        if (count != 0) return new int[0];
        return res;
    }
}
